<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MBonusLog;
use App\Models\MConsumeLog;
use App\Models\MDebitLog;
use App\Models\MLog;
use App\Models\MLoginLog;
use App\Models\MMoneyLog;
use App\Models\MRemitLog;
use App\Models\MScore;
use App\Models\MTransferLog;
use App\Models\MUser;
use App\Models\MWallet;
use App\Models\MWithdrawLog;
use App\Utils\TreeUtil;
use App\VModels\VVip;
use DB;
use Exception;
use Illuminate\Http\Request;


/**
 * 后台登录控制器
 */
class WorkerController extends Controller
{
    /**
     * 默认系统欢迎页
     */
    public function welcomePage()
    {
        return view("admin.welcome");
    }

    /**
     * 会员统计页
     */
    public function userCount()
    {

        //系统会员注册激活
        $dates = array();//日期数组
        $regUserNums = array();//注册用户数组
        $okUserNums = array();//激活用户数组
        $loginUserNums = array();//登录用户数量数组
        for ($i = 0; $i < 7; $i++) {
            $beginToday = mktime(0, 0, 0, date('m'), date('d') - $i, date('Y'));
            $endToday = mktime(0, 0, 0, date('m'), date('d') + 1 - $i, date('Y')) - 1;
            array_unshift($dates, date("Y/m/d", $beginToday));

            $regUserNum = MUser::whereBetween('reg_time', [$beginToday, $endToday])->count();
            array_unshift($regUserNums, $regUserNum);

            $okUserNum = MUser::whereBetween('ok_time', [$beginToday, $endToday])->count();
            array_unshift($okUserNums, $okUserNum);

            $loginUser = MLoginLog::whereBetween('time', [$beginToday, $endToday])->groupBy('uid')->get();
            $loginUserNum = count($loginUser);
            array_unshift($loginUserNums, $loginUserNum);
        }

        $this->data['dates'] = json_encode($dates);
        $this->data['regUserNums'] = json_encode($regUserNums);
        $this->data['okUserNums'] = json_encode($okUserNums);
        $this->data['loginUserNums'] = json_encode($loginUserNums);

        //会员等级占比
        //会员等级占比
        $vipData = [];
        $vip0 = MUser::where('vip_slug', MUser::$VIP_0)->count();
        if ($vip0 != 0) {
            array_unshift($vipData, ['value' => $vip0, 'name' => VVip::vipBySlug(MUser::$VIP_0)->name]);
        }

        $vip1 = MUser::where('vip_slug', MUser::$VIP_1)->count();
        if ($vip1 != 0) {
            array_unshift($vipData, ['value' => $vip1, 'name' => VVip::vipBySlug(MUser::$VIP_1)->name]);
        }

        $vip2 = MUser::where('vip_slug', MUser::$VIP_2)->count(); //金级会员
        if ($vip2 != 0) {
            array_unshift($vipData, ['value' => $vip2, 'name' => VVip::vipBySlug(MUser::$VIP_2)->name]);
        }

        $vip3 = MUser::where('vip_slug', MUser::$VIP_3)->count(); //钻级会员
        if ($vip3 != 0) {
            array_unshift($vipData, ['value' => $vip3, 'name' => VVip::vipBySlug(MUser::$VIP_3)->name]);
        }


        //会员数字信息统计
        $this->data['okUsers'] = MUser::where('ok_status', 1)->count();
        $this->data['noOkUsers'] = MUser::where('ok_status', 0)->count();
        $this->data['bdzxUsers'] = MUser::where('bdzx_status', 1)->count();
        $this->data['inUsers'] = MUser::where('in', 1)->count();
        $this->data['sumUsers'] = MUser::all()->count();
        $this->data['vipData'] = json_encode($vipData);

        return view("admin.user_count")->with($this->data);
    }

    /**
     * 资金报表数据统计
     * @return $this
     */
    public function moneyStatement()
    {
//        $nowTime = strtotime(date('Y-m-d', strtotime('now')));       //今天的0点时间戳
//        $aWeekAgo = strtotime(date('Y-m-d', strtotime('-6 day')));   //6天前的0点时间戳

        $in = [];
        $out = [];
        $b1 = [];
        $b2 = [];
        $b3 = [];
        $b4 = [];
        $b5 = [];
        $b6 = [];
        $date = []; //日期

        for ($i = 0; $i < 7; $i++) {
            $b_time[$i] = strtotime(date("Y-m-d", strtotime("-$i day")));
            if ($i == 0) {
                $e_time[$i] = strtotime('now');
            } else {
                $e_time[$i] = strtotime(date("Y-m-d", strtotime("-" . ($i - 1) . " day")));
            }
            $moneyLogs[$i] = MMoneyLog::where('time', '>=', $b_time[$i])->where('time', '<', $e_time[$i])->orderBy('time')->get();

            if ($moneyLogs[$i]->isEmpty()) {
                array_unshift($in, "0.00");
                array_unshift($out, "0.00");
                array_unshift($b1, "0.00");
                array_unshift($b2, "0.00");
                array_unshift($b3, "0.00");
                array_unshift($b4, "0.00");
                array_unshift($b5, "0.00");
                array_unshift($b6, "0.00");
                array_unshift($date, date("Y/m/d", $b_time[$i]));
            } else {
                foreach ($moneyLogs[$i] as $log) {
                    array_unshift($in, $log->in);
                    array_unshift($out, $log->out);
                    array_unshift($b1, $log->b1);
                    array_unshift($b2, $log->b2);
                    array_unshift($b3, $log->b3);
                    array_unshift($b4, $log->b4);
                    array_unshift($b5, $log->b5);
                    array_unshift($b6, $log->b6);
                    array_unshift($date, date("Y/m/d", $log->time));
                }
            }
        }

        $this->data['in'] = json_encode($in);
        $this->data['out'] = json_encode($out);
        $this->data['date'] = json_encode($date);
        $this->data['b1'] = json_encode($b1);
        $this->data['b2'] = json_encode($b2);
        $this->data['b3'] = json_encode($b3);
        $this->data['b4'] = json_encode($b4);
        $this->data['b5'] = json_encode($b5);
        $this->data['b6'] = json_encode($b6);

        $this->data['score'] = MScore::find(1, ['a_count', 'b_count', 'a_over', 'b_over']); //根节点业绩结余

        return view("admin.money_statement")->with($this->data);
    }

    /**
     * 提现申请列表页
     * $flag = 0 申请中的提现列表
     * $flag = 1 已打款的提现列表
     * $flag = 2 已拒绝的提现列表
     */
    public function withdrawPage(Request $request, $flag, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('admin.withdraw', ['flag' => $flag]), 15, $request->getQueryString());
        $query = (new MWithdrawLog())->query();

        //按类别筛选
        $this->data['flag'] = $flag;
        if ($flag == 0) {
            $query = $query->where('status', MWithdrawLog::$STATUS_WAIT);
        } elseif ($flag == 1) {
            $query = $query->where('status', MWithdrawLog::$STATUS_SUCCESS);
        } elseif ($flag == 2) {
            $query = $query->where('status', MWithdrawLog::$STATUS_DENY);
        }

        //指定了按时间段搜索
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //指定了搜索条件
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {       //按会员用户名搜索
                $query = $query->where('username', 'like', "%" . $request->search_str . "%");

            } elseif ($request->search_type == 2) { //按提现申请唯一编号搜索
                $query = $query->where('no', $request->search_str);

            } elseif ($request->search_type == 3) { //按会员ID搜索
                $query = $query->where('id', 'like', $request->search_str);

            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['withdraws'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('create_time', 'desc')
            ->get();

        $this->fyViewInit($this->data);
        return view('admin.withdraw')->with($this->data);
    }

    /**
     * 通过用户提现申请
     */
    public function allowWithdraw(Request $request)
    {
        if (!$request->has(['text', 'id'])) {
            $this->data = $this->makeJsCode(1, "请填写详细的拒绝理由！");
            return back()->with($this->data);
        }

        $log = MWithdrawLog::find($request->id);
        if (empty($log)) {
            $this->data = $this->makeJsCode(1, "提现申请单无效！");
            return back()->with($this->data);
        }

        try {
            DB::transaction(function () use (&$request, &$log) {
                if ($log->allow($request->text)) {
                    $this->data = $this->makeJsCode(0, "操作成功! ");
                    MLog::log("通过了用户 $log->username ( ID: $log->uid ) 发出的编号为 $log->no 的提现申请单!");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败! ");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作失败，请重新尝试！");
        }

        return back()->with($this->data);
    }

    /**
     * 拒绝用户提现申请
     */
    public function denyWithdraw(Request $request)
    {
        if (!$request->has(['text', 'id'])) {
            $this->data = $this->makeJsCode(1, "请填写详细的拒绝理由！");
            return back()->with($this->data);
        }

        $log = MWithdrawLog::find($request->id);
        if (empty($log)) {
            $this->data = $this->makeJsCode(1, "提现申请单无效！");
            return back()->with($this->data);
        }

        try {
            DB::transaction(function () use (&$request, &$log) {
                if ($log->deny($request->text)) {
                    $this->data = $this->makeJsCode(0, "操作成功! ");
                    MLog::log("拒绝了用户 $log->username ( ID: $log->uid ) 发出的编号为 $log->no 的提现申请单!");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败! ");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "拒绝失败，请重新尝试！");
        }
        return back()->with($this->data);
    }

    /**
     * 打款申请列表页
     * @param Request $request
     * @param $flag 0显示未处理记录 1显示已处理记录
     * @param int $index
     * @return $this
     */
    public function remitPage(Request $request, $flag, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('admin.remit', ['flag' => $flag]), 15, $request->getQueryString());
        $query = (new MRemitLog())->query();

        //按类别筛选
        $this->data['flag'] = $flag;
        if ($flag == 0) {
            $query = $query->where('status', MRemitLog::remit_pay);
        } elseif ($flag == 1) {
            $query = $query->where('status', MRemitLog::remit_yes)->orWhere('status', MRemitLog::remit_no);
        }

        //指定了按时间段搜索
        if ($request->has(['start', 'end'])) {
            $query = $query->where($request->time_type, '>=', strtotime($request->start))
                ->where($request->time_type, '<=', strtotime($request->end));
        }

        //指定了搜索条件
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {       //按打款申请唯一编号搜索
                $query = $query->where('no', $request->search_str);

            } elseif ($request->search_type == 2) { //按打款申请ID搜索
                $query = $query->where('id', $request->search_str);

            } elseif ($request->search_type == 3) { //按会员用户名搜索
                $query = $query->where('username', 'like', '%' . $request->search_str . '%');

            } elseif ($request->search_type == 4) { //按注册手机号
                $user = MUser::where("mobile", $request->search_str)->first();
                if ($user) {
                    $query = $query->where('username', $user->username);
                }

            } elseif ($request->search_type == 5) { //按会员编号
                $user = MUser::where("no", $request->search_str)->first();
                if ($user) {
                    $query = $query->where('username', $user->username);
                }

            } elseif ($request->search_type == 6) { //按真实姓名
                $query = $query->where('realname', 'like', '%' . $request->search_str . '%');

            } elseif ($request->search_type == 7) { //按支付宝账号
                $query = $query->where('zfb', 'like', '%' . $request->search_str . '%');

            } elseif ($request->search_type == 8) { //按微信账号
                $query = $query->where('wx', 'like', '%' . $request->search_str . '%');

            } elseif ($request->search_type == 9) { //按银行卡号
                $query = $query->where('card_no', 'like', '%' . $request->search_str . '%');

            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['remitLogs'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)
            ->orderBy('status', 'asc')
            ->orderBy('create_time', 'desc')
            ->get();

        $this->fyViewInit($this->data);
        return view('admin.remit')->with($this->data);
    }

    /**
     * 同意打款申请
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function allowRemit(Request $request)
    {
        if (!$request->has(['text', 'id'])) {
            $this->data = $this->makeJsCode(1, "请填写详细的处理结果，以便用户查看！");
            return back()->with($this->data);
        }

        $log = MRemitLog::find($request->id);
        if (empty($log)) {
            $this->data = $this->makeJsCode(1, "打款申请单无效！");
            return back()->with($this->data);
        }

        $username = $log->user->username;
        try {
            DB::transaction(function () use (&$request, &$log, $username) {
                if ($log->allow($request->text)) {
                    $wallet = MWallet::where('uid', $log->uid)->first();
                    //充值
                    if ($log->wallet == MWallet::$WALLET_TYPE_1) {
                        $wallet->w1 += $log->money;
                    } elseif ($log->wallet == MWallet::$WALLET_TYPE_2) {
                        $wallet->w2 += $log->money;
                    } elseif ($log->wallet == MWallet::$WALLET_TYPE_3) {
                        $wallet->w3 += $log->money;
                    }

                    //充值记录
                    $consume = MConsumeLog::log(
                        $log->uid, $log->username, $log->money,
                        MConsumeLog::$CONSUME_RECHARGE, $log->wallet,
                        "打款申请单通过，" . uWalletStr($log->wallet) . "充值 $log->money 元"
                    );

                    $sysLog = MLog::log("通过了用户 $username ( ID: $log->uid ) 发出的编号为 $log->no 的打款申请单!");
                    if ($wallet->save() && $consume && $sysLog) {
                        $this->data = $this->makeJsCode(0, "操作成功! ");
                    } else {
                        DB::rollBack();
                        $this->data = $this->makeJsCode(1, "操作失败! ");
                    }

                } else {
                    $this->data = $this->makeJsCode(1, "操作失败! ");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作失败，请重新尝试！");
        }

        return back()->with($this->data);
    }

    /**
     * 拒绝打款申请
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function denyRemit(Request $request)
    {
        if (!$request->has(['text', 'id'])) {
            $this->data = $this->makeJsCode(1, "请填写详细的拒绝打款理由！");
            return back()->with($this->data);
        }

        $log = MRemitLog::find($request->id);
        if (empty($log)) {
            $this->data = $this->makeJsCode(1, "提现申请单无效！");
            return back()->with($this->data);
        }

        $username = $log->user->username;

        try {
            DB::transaction(function () use (&$request, &$log, $username) {
                if ($log->deny($request->text)) {
                    $this->data = $this->makeJsCode(0, "操作成功! ");
                    MLog::log("拒绝了用户 $username ( ID: $log->uid ) 发出的编号为 $log->no 的提现申请单!");
                } else {
                    $this->data = $this->makeJsCode(1, "操作失败! ");
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作失败，请重新尝试！");
        }
        return back()->with($this->data);
    }

    /**
     * 充值/扣款 界面
     */
    public function debitPage(Request $request)
    {
        return view('admin.debit');
    }

    /**
     * 充值/扣款 功能实现
     * $flag = 0 充值 = 1 扣款
     */
    public function debitSave(Request $request, $flag)
    {
        //对会员信息进行再次验证
        if (!$request->has(['uname', 'money', 'type'])) {
            $this->data = $this->makeJsCode(1, "信息填写不完整");
            return response()->json($this->data);
        }

        //检查用户是否存在
        $user = MUser::where('username', $request->uname)->first();
        if (empty($user)) {
            $this->data = $this->makeJsCode(1, "该用户不存在!");
            return response()->json($this->data);
        }

        //检查充值或扣款数字是否合法
        if ($request->input("money") <= 0) {
            $this->data = $this->makeJsCode(1, "充值金额必须 > 0");
            return response()->json($this->data);
        }

        try {
            DB::transaction(function () use (&$request, &$user, $flag) {
                $wallet = $user->wallet;
                if ($flag == MDebitLog::$USER_RECHARGE) {   //钱包充值
                    if ($wallet->recharge($request->type, $request->money)) {
                        $this->data = $this->makeJsCode(0, "充值成功！");
                        MDebitLog::log($user->id, $user->username, $request->money,
                            $flag, $request->type);
                        MConsumeLog::log($user->id, $user->username, $request->money, MConsumeLog::$CONSUME_RECHARGE,
                            $request->type, "后台为您的账户充值成功！");

                    } else {
                        DB::rollBack();
                        $this->data = $this->makeJsCode(0, "充值失败！");
                    }
                } elseif ($flag == MDebitLog::$USER_DEDUCTING) {    //钱包扣款
                    if ($wallet->deducting($request->type, $request->money)) {
                        $this->data = $this->makeJsCode(0, "扣款成功！");
                        MDebitLog::log($user->id, $user->username, $request->money,
                            $flag, $request->type);
                        MConsumeLog::log($user->id, $user->username, $request->money, MConsumeLog::$CONSUME_DEDUCTING,
                            $request->type, "后台为您的账户扣款成功！");

                    } else {
                        DB::rollBack();
                        $this->data = $this->makeJsCode(0, "扣款失败！");
                    }
                }
            });
        } catch (Exception $e) {
            $this->data = $this->makeJsCode(1, "操作发生错误！");
        }

        return response()->json($this->data);
    }

    /**
     * 充值/扣款记录
     */
    public function debitLogPage(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route("admin.debit.log"), 20, $request->getQueryString());
        $query = (new MDebitLog())->query();

        //按时间过滤
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //指定了搜索条件
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {       //按用户帐号搜索
                $query = $query->where('username', 'like', "%" . $request->search_str . "%");

            } elseif ($request->search_type == 2) { //按用户编号搜索
                $user = MUser::where("no", $request->search_str)->first();
                $query = $query->where("uid", isset($user->id) ? ($user->id) : 0);

            } elseif ($request->search_type == 3) { //按用户ID搜索
                $query = $query->where('uid', $request->search_str);

            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['logs'] = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)->orderBy('time', 'desc')->get();
        $this->fyViewInit($this->data);

        return view("admin.debit_logs")->with($this->data);
    }

    /**
     * 奖金明细页面
     */
    public function bonusLogPage(Request $request, $index = 1)
    {
        //开启分页搜索
        $this->fyInit(route('admin.bonus'), 20, $request->getQueryString());
        $query = (new MBonusLog())->query();

        //指定了搜索条件
        if ($request->has(['start'])) {
            $query = $query->where("time", ">=", strtotime($request->start));
        }

        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {        //按用户账号搜索
                $query = $query->where("username", "like", "%" . $request->search_str . "%");

            } elseif ($request->search_type == 2) {   //按用户编号
                $user = MUser::where("no", $request->search_str)->first();
                $query = $query->where("uid", isset($user->id) ? ($user->id) : 0);

            } elseif ($request->search_type == 3) {    //按用户ID搜索
                $query = $query->where("uid", $request->search_str);

            }

        }

        $this->fyCalc($query->count(), $index);
        $this->data['bonus'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->orderBy('time', 'desc')->get();

        $this->fyViewInit($this->data);
        return view('admin.bonus')->with($this->data);
    }

    /**
     * 转账记录
     */
    public function transferLogPage(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route('admin.transfer'), 20, $request->getQueryString());
        $query = (new MTransferLog())->query();

        //按时间过滤
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //按用户帐号过滤
        if ($request->has(['search', 'search_str']) && $request->search == 1) {
            $query = $query->where('username', 'like', "%" . $request->search_str . "%");
        }

        //按用户ID过滤
        if ($request->has(['search', 'search_str']) && $request->search == 2) {
            $query = $query->where('uid', $request->search_str);
        }

        //按用户编号过滤
        if ($request->has(['search', 'search_str']) && $request->search == 3) {
            $user = MUser::where("no", $request->search_str)->first();
            $query = $query->where("uid", isset($user->id) ? ($user->id) : 0);
        }

        $this->fyCalc($query->count(), $index);
        $this->data['logs'] = $query->skip($this->fy_pgOffset)
            ->take($this->fy_pgSize)->orderBy('time', 'desc')->get();

        $this->fyViewInit($this->data);
        return view('admin.transfer_logs')->with($this->data);
    }

    /**
     * 会员消费明细界面
     */
    public function consumeLogPage(Request $request, $index = 1)
    {
        //开启分页搜索支持
        $this->fyInit(route("admin.consume"), 20, $request->getQueryString());
        $query = (new MConsumeLog())->query();

        //按时间过滤
        if ($request->has(['start', 'end'])) {
            $query = $query->where('time', '>=', strtotime($request->start))
                ->where('time', '<=', strtotime($request->end));
        }

        //指定了搜索条件
        if ($request->has(['search_type', 'search_str'])) {
            if ($request->search_type == 1) {       //按用户帐号搜索
                $query = $query->where('username', 'like', "%" . $request->search_str . "%");

            } elseif ($request->search_type == 2) { //按用户编号搜索
                $user = MUser::where("no", $request->search_str)->first();
                $query = $query->where("uid", isset($user->id) ? ($user->id) : 0);

            } elseif ($request->search_type == 3) { //按用户ID搜索
                $query = $query->where('uid', $request->search_str);

            }
        }

        $this->fyCalc($query->count(), $index);
        $this->data['logs'] = $query->skip($this->fy_pgOffset)->take($this->fy_pgSize)->orderBy('time', 'desc')->get();

        $this->fyViewInit($this->data);
        return view('admin.consume_logs')->with($this->data);
    }


}